package top.crossrun.webview.bridge.core.pls;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;

import top.crossrun.webview.bridge.core.utils.BridgeUtil;

/**
 * 插件
 */
public abstract class WebViewBridgePlugin implements WebViewBridgeHandler {

    private WebViewBridgePluginManager bridgePluginManager;
    private boolean needContext = true;
    private String pluginName;

    /**
     * 处理H5发来的交互信息
     *
     * @param data
     * @param callBackFunction
     */
    public void _handlerBridgeMsg(String data, BridgeCallBackFunction callBackFunction) {
        if (needContext && (getBridgePluginManager() == null || getContext() == null || getContext().isDestroyed())) {
            return;
        }
        handlerBridgeMsg(data, callBackFunction);
    }

    public WebViewBridgePlugin() {

    }

    public WebViewBridgePlugin(String pluginName) {
        this(pluginName, true);
    }

    public WebViewBridgePlugin(String pluginName, boolean needContext) {
        this.needContext = needContext;
        this.pluginName = pluginName;
    }

    public void onDestroy() {
        bridgePluginManager = null;
    }

    public String getPluginName() {
        if (!TextUtils.isEmpty(pluginName)) {
            return pluginName;
        }
        String s = getClass().getSimpleName();
        int f = s.charAt(0);
        if (f >= 65 && f <= 90) {
            char[] chars = s.toCharArray();
            chars[0] += 32;
            return String.valueOf(chars);
        }
        return s;
    }

    public void notifyData(BridgePluginMsg msg) {

    }

    /**
     * @param intent
     * @return true = 启动成功;false = 没找到intent对应的Activity
     */
    public boolean startActivity(Intent intent) {
        if (BridgeUtil.isIntentAvailable(getContext(), intent)) {
            getContext().startActivity(intent);
            return true;
        }
        return false;
    }

    public Activity getContext() {
        return bridgePluginManager.getActivityContext();
    }

    public WebViewBridgePluginManager getBridgePluginManager() {
        return bridgePluginManager;
    }

    public void setBridgePluginManager(WebViewBridgePluginManager bridgePluginManager) {
        this.bridgePluginManager = bridgePluginManager;
    }

}

